import { defineStore } from 'pinia'
import { IBudgetInfo, IBudgetQuery } from '@/types/budget'
import {
  addBudgetApi, deleteBudgetApi,
  queryBudgetApi,
  queryBudgetCategory,
  queryBudgetProjectStats,
  queryBudgetRankStats, updateBudgetApi
} from '@/apis/budget'
import type { IDialog, IHandleApi, IShowData, IStatsChart } from 'vue3-common/types'
import { ElMessage } from 'element-plus'

export const useBudgetStore = defineStore('budget', {
  state: () => ({
    budgetList: [] as IBudgetInfo[],
    budgetCategoryList: [] as string[],
    queryInfo: {
      category: ''
    } as IBudgetQuery,
    budgetApiType: 'ADD' as IHandleApi,
    budgetDialog: {
      visible: false,
      title: '',
      data: {}
    } as IDialog<IBudgetInfo>,
    isRefresh: false,
    showDataType: 'DATA' as IShowData,
    budgetRankStatsList: [] as IStatsChart[],
    budgetProjectStatsList: [] as IStatsChart[]
  }),
  actions: {
    async queryBudget() {
      this.budgetList = await queryBudgetApi(this.queryInfo.category)
    },
    async queryBudgetCategory() {
      this.budgetCategoryList = await queryBudgetCategory()
    },
    async queryBudgetStats() {
      this.budgetRankStatsList = await queryBudgetRankStats(this.queryInfo.category)
      this.budgetProjectStatsList = await queryBudgetProjectStats(this.queryInfo.category)
    },
    async handleBlogApi(id?: number) {
      switch (this.budgetApiType) {
        case 'ADD':
          await addBudgetApi(this.budgetDialog.data)
          ElMessage.success('新增预算成功')
          break
        case 'UPDATE':
          await updateBudgetApi(id as number, this.budgetDialog.data)
          ElMessage.success('更新预算成功')
          break
        case 'DELETE':
          await deleteBudgetApi(id as number)
          ElMessage.success('删除预算成功')
          break
        default:
          break
      }
      this.budgetDialog.visible = false
      await this.refreshInfo()
    },
    async refreshInfo() {
      switch (this.showDataType) {
        case 'DATA':
          await this.queryBudget()
          break
        case 'CHART':
          await this.queryBudgetStats()
          break
        default:
          break
      }
      this.isRefresh = !this.isRefresh
    },
    getEmptyBudget(): IBudgetInfo {
      return {
        actual: 0,
        budget: 0,
        category: '',
        content: '',
        payTime: '',
        project: '',
        remake: '',
        vendor: ''
      }
    }
  }
})
